package com.wickywe.common.Lottery;

import java.util.List;
import java.util.Random;

/**
 * 抽奖逻辑
 */
public class LotteryUtils {

    private static final Random random = new Random();
    private static final Integer MAXSOPE = 100000000;

    public static void calAwardProbability(Lottery lottery, List<LotteryItem> lotteryItemList) {
        Integer codeScope = 1;
        for (LotteryItem item : lotteryItemList) {
            Integer nowScope = 1;
            Double awardProbability = item.getAwardProbability();
            while (true) {
                Double test = awardProbability * nowScope;
                // 概率的精确度，调整到小数点后10位，概率太小等于不中奖，跳出
                if (test < 0.0000000001) {
                    break;
                }
                if ((test >= 1L && (test - test.longValue()) < 0.0001D) || nowScope >= MAXSOPE) {
                    if (nowScope > codeScope) {
                        // 设置中奖范围
                        codeScope = nowScope;
                    }
                    break;
                } else {
                    // 中奖数字范围以10倍进行增长
                    nowScope = nowScope * 10;
                }
            }
        }
        Integer winningStartCode = 0;
        Integer winningEndCode = winningStartCode;

        for (LotteryItem item : lotteryItemList) {
            Integer codeNum = (int) (item.getAwardProbability() * codeScope); // 获得其四舍五入的整数值
            // 无人中奖时，将中奖的起始范围设置在随机数的范围之外
            if (codeNum == 0) {
                item.setAwardStartCode(codeScope + 1);
                item.setAwardEndCode(codeScope + 1);
            } else {
                item.setAwardStartCode(winningEndCode);
                item.setAwardEndCode(winningEndCode + codeNum - 1);
                winningEndCode = winningEndCode + codeNum;
            }
        }
        // 设置用户的中奖随机码信息
        lottery.setWinningStartCode(winningStartCode);
        lottery.setWinningEndCode(winningEndCode);
        lottery.setCodeScope(codeScope);
    }

    public static LotteryItem beginLottery(Lottery lottery, List<LotteryItem> lotteryItemList) {
        // 确定活动是否有效,如果活动无效则，直接抽奖失败
        Integer randomCode = random.nextInt(lottery.getCodeScope());
        if (randomCode >= lottery.getWinningStartCode() && randomCode <= lottery.getWinningEndCode()) {
            for (LotteryItem item : lotteryItemList) {
                if (randomCode >= item.getAwardStartCode() && randomCode <= item.getAwardEndCode()) {
                    item.setAwardCode(randomCode);
                    return item;
                }
            }
        }
        return null;
    }

}
